package com.topcent.tioxyc.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.pojo.vo.BCDesignAppVO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 陈百万
 * @date: 2025/4/16 15:48
 * @Description: 采购订单到简道云表单
 */
@Slf4j
@RestController
public class PurchaseOrderYunController {
    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    /**
     * 采购单数据-简道云
     *
     * @return
     */
    @GetMapping("purchaseOrderYunData")
    public String purchaseOrderYunData() {
        String appId = "67f8aa2676b9b3942c49035f";
        String entryId = "67ff675568c6ea7be7efebe9";
        Header[] headers = ConnmeUtils.createHeaders();
        //批量删除简道云数据
        ConnmeUtils.selectAndDeleteList(headers, appId, entryId, "");
        // 获取原始数据
        List<PurchaseOrderList> originalData = yy1KpiMapper.selectPurchaseOrderAll();

        // 获取用户人员信息
        Map<String ,Object> person =new HashMap<>();
        person.put("dept_no", 1);
        person.put("has_child", true);
        JSONObject personResult = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/corp/department/user/list", headers, JSONUtil.toJsonStr(person));
        String personData = personResult.getStr("users");
        JSONArray personObjects = JSONUtil.parseArray(personData);
        List<Assignee> personList = JSONUtil.toList(personObjects, Assignee.class);

        Map<String, String> userNameMap = personList.stream()
                .collect(Collectors.toMap(Assignee::getName, Assignee::getUsername, (v1, v2) -> v1));
        // 按供应商分组
        Map<String, List<PurchaseOrderList>> groupedBySupplier = originalData.stream()
                .collect(Collectors.groupingBy(PurchaseOrderList::getSupplier));

        // 遍历每组
        for (Map.Entry<String, List<PurchaseOrderList>> entry : groupedBySupplier.entrySet()) {
            List<PurchaseOrderList> list = entry.getValue();

            // 找出该组中最晚的订单时间
            Optional<String> latestDateOpt = list.stream()
                    .map(PurchaseOrderList::getPurchaseOrderDate)
                    .filter(Objects::nonNull)
                    .max(String::compareTo);

            if (latestDateOpt.isPresent()) {
                String latestDate = latestDateOpt.get();
                // 给每条记录设置相同的最新时间
                list.forEach(po -> po.setRecentTime(latestDate));
            }
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        // 将处理后的数据存入简道云
        for (PurchaseOrderList entity : originalData) {
            if (entity.getDeliveredQuantity() != null && entity.getDeliveredQuantity() < 0) {
                if (entity.getConditionAmount_1() != null && entity.getConditionAmount_1().compareTo(BigDecimal.ZERO) > 0) {
                    entity.setConditionAmount_1(entity.getConditionAmount_1().negate());
                }

                if (entity.getOrderQuantity() != null && !entity.getOrderQuantity().startsWith("-")) {
                    entity.setOrderQuantity("-" + entity.getOrderQuantity());
                }
                if (entity.getOrderQuantity1() != null && !entity.getOrderQuantity1().startsWith("-")) {
                    entity.setOrderQuantity1("-" + entity.getOrderQuantity1());
                }

                if (entity.getNetAmount() != null && !entity.getNetAmount().startsWith("-")) {
                    entity.setNetAmount("-" + entity.getNetAmount());
                }
                if (entity.getNetAmount1() != null && !entity.getNetAmount1().startsWith("-")) {
                    entity.setNetAmount1("-" + entity.getNetAmount1());
                }
                if (entity.getConditionAmount() != null && !entity.getConditionAmount().startsWith("-")) {
                    entity.setConditionAmount("-" + entity.getConditionAmount());
                }

                if (entity.getNetPriceAmount() != null && !entity.getNetPriceAmount().startsWith("-")) {
                    entity.setNetPriceAmount("-" + entity.getNetPriceAmount());
                }
                if (entity.getNetPriceAmount1() != null && !entity.getNetPriceAmount1().startsWith("-")) {
                    entity.setNetPriceAmount1("-" + entity.getNetPriceAmount1());
                }
                if (entity.getConditionRateValue() != null && !entity.getConditionRateValue().startsWith("-")) {
                    entity.setConditionRateValue("-" + entity.getConditionRateValue());
                }
                if (entity.getConditionRateValue1() != null && !entity.getConditionRateValue1().startsWith("-")) {
                    entity.setConditionRateValue1("-" + entity.getConditionRateValue1());
                }
            }

            ZPurchaseOrderList vo = new ZPurchaseOrderList();
            vo.set_widget_1744791381513(entity.getPurchaseOrder());vo.set_widget_1744791381514(entity.getPurchaseOrderItem());vo.set_widget_1744791381515(entity.getPurchaseOrderType());vo.set_widget_1744791381516(entity.getPurchasingDocumentTypeName());
            vo.set_widget_1744791381517(entity.getSupplier());vo.set_widget_1744791381518(entity.getSupplierName());vo.set_widget_1744791381519(entity.getPurchaseOrderDate());vo.set_widget_1744791381520(entity.getPaymentTerms());
            vo.set_widget_1744791381521(entity.getPaymentTermsName());vo.set_widget_1744791381522(entity.getPurchaseOrderItemCategory());vo.set_widget_1744791381523(entity.getPurgDocItemCategoryName());
            vo.set_widget_1744791381524(entity.getAccountAssignmentCategory());vo.set_widget_1744791381525(entity.getAcctAssignmentCategoryName());
            vo.set_widget_1744791381526(entity.getMaterial());vo.set_widget_1744791381527(entity.getPurchaseOrderItemText());
            String quantityStr = entity.getOrderQuantity();
            vo.set_widget_1744941776389(
                    (quantityStr == null || quantityStr.trim().isEmpty()) ? null : Integer.valueOf(quantityStr)
            );
            String quantityStr1 = entity.getOrderQuantity1();
            vo.set_widget_1744941776388(
                    (quantityStr1 == null || quantityStr1.trim().isEmpty()) ? null : Integer.valueOf(quantityStr1)
            );
            vo.set_widget_1744791381530(entity.getPurchaseOrderQuantityUnit());
            vo.set_widget_1744791381531(entity.getUnitOfMeasureLongName());vo.set_widget_1744791381532(entity.getNetPriceAmount());
            vo.set_widget_1744791381533(entity.getNetPriceAmount1());vo.set_widget_1744791381534(entity.getConditionRateValue());
            vo.set_widget_1744791381535(entity.getConditionRateValue1());vo.set_widget_1744791381536(entity.getConditionCurrency());vo.set_widget_1744791381537(entity.getNetAmount());vo.set_widget_1744791381538(entity.getNetAmount1());
            vo.set_widget_1744791381539(entity.getConditionAmount());vo.set_widget_1744791381540(entity.getDocumentCurrency());vo.set_widget_1744791381541(entity.getConditionQuantity());
            vo.set_widget_1744791381542(entity.getConditionQuantityUnit());vo.set_widget_1744791381543(entity.getTax());vo.set_widget_1744791381544(entity.getMaterialGroup());vo.set_widget_1744791381545(entity.getMaterialGroupName());
            vo.set_widget_1744791381546(entity.getPlant());vo.set_widget_1744791381547(entity.getPlantName());
            vo.set_widget_1744791381548(entity.getStorageLocation());vo.set_widget_1744791381549(entity.getStorageLocationName());
            vo.set_widget_1744791381550(entity.getScheduleLineDeliveryDate());vo.set_widget_1744791381551(entity.getIsReturnsItem());vo.set_widget_1744791381552(entity.getPurchaseRequisition());vo.set_widget_1744791381553(entity.getPurchaseRequisitionItem());vo.set_widget_1744791381554(entity.getSalesOrder());vo.set_widget_1744791381555(entity.getSalesOrderItem());
            vo.set_widget_1744791381556(entity.getYY1_ZBMCL_PO_PDI());vo.set_widget_1744791381557(entity.getYY1_ZCPJZ_PO_PDI());vo.set_widget_1744791381558(entity.getYY1_ZPJ_PO_PDI());
            vo.set_widget_1744791381559(entity.getYY1_ZBZXX_PO_PDI());vo.set_widget_1744791381560(entity.getYY1_ZCL_PO_PDI());
            vo.set_widget_1744791381561(entity.getYY1_KS_PO_PDI());vo.set_widget_1744791381562(entity.getYY1_ZGGCC_PO_PDI());
            vo.set_widget_1744791381563(entity.getVCDescription());vo.set_widget_1744877640041(entity.getPurchasingGroupName());
            vo.set_widget_1744791381565(entity.getAddressSearchTerm1());vo.set_widget_1744791381566(entity.getSupplierRespSalesPersonName());
            vo.set_widget_1744791381567(entity.getAuthorizationGroupText());vo.set_widget_1744791381568(entity.getBusinessPartnerName1());
            vo.set_widget_1744791381569(entity.getPersonFullName());vo.set_widget_1744791381570(entity.getPurchasingDocumentDeletionCode());
            vo.set_widget_1744791381571(entity.getIsCompletelyDelivered());vo.set_widget_1744791381572(entity.getCurrency());
            vo.set_widget_1744791381573(entity.getExchangeRate());vo.set_widget_1744791381574(entity.getUnitOfMeasure());
            vo.set_widget_1744791381575(entity.getPurchasingProcessingStatus());vo.set_widget_1744791381576(entity.getDivision());
            vo.set_widget_1744791381577(entity.getPersonFullName_1());vo.set_widget_1744791381578(entity.getTaxCode());
            vo.set_widget_1744791381579(entity.getExchangeRate_1());vo.set_widget_1744791381580(entity.getSalesOffice());vo.set_widget_1744791381581(entity.getGlobalCurrency());vo.set_widget_1744791381582(entity.getSalesOrganization());vo.set_widget_1744795545795(entity.getRecentTime());vo.set_widget_1744877326805(entity.getProductType());vo.set_widget_1744941776391(entity.getProductTypeName());
            vo.set_widget_1744946520199(entity.getDeliveredQuantity());vo.set_widget_1744946520200(entity.getConditionAmount_1());vo.set_widget_1745202497032(entity.getDeliveredAmount());vo.set_widget_1745223232087(entity.getValuationClass());

            String username = userNameMap.get(vo.get_widget_1744877640041());
            if (username != null) {
                vo.set_widget_1744877640041(username);
            }
            vo.set_id(null);
            mapList.add(ConnmeUtils.convertEntityToMap(vo));
        }
        //批量新增到简道云
        ConnmeUtils.batchAddList(headers, appId, entryId, mapList);
        return "success数量：" + mapList.size();
    }

    /**
     * 包材设计申请-简道云
     *
     * @return
     */
    @GetMapping("pmDesignApp")
    public String pmDesignApp() {
        Header[] headers = ConnmeUtils.createHeaders();
        List<BCDesignAppVO> bcDesignAppVOList = new ArrayList<>();
        String appId = "64ee9c37ee0a2c0007bc7afc";
        String entryId = "63edf3a123c2e70009100e2d";

        // 获取到包材设计申请进行中的数据
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", appId);
        parameter.put("entry_id", entryId);

        /*Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "eq");
        List<Integer> values = new ArrayList<>();
        values.add(0);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);*/

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<BCDesignAppVO> list = JSONUtil.toList(objects, BCDesignAppVO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            bcDesignAppVOList.addAll(list);
        } while (fale);

        // 查询进行中数据的审核流程状态。
        for (BCDesignAppVO bcDesignAppVO : bcDesignAppVOList) {
            String flowState = bcDesignAppVO.getFlowState(); // 流程状态：2表示流程手动结束；1表示流程已完成；0表示流程进行中
            if(flowState.equals("2")){
                continue;
            }
            Map<String, Object> parameterExam = new HashMap<>();
            parameterExam.put("instance_id", bcDesignAppVO.get_id());
            parameterExam.put("tasks_type", 1);
            String jsonSale = JSONUtil.toJsonStr(parameterExam);
            JSONObject jdySale = ApiClient.sendPostRequest("https://api.jiandaoyun.com/api/v5/workflow/instance/get", headers, jsonSale);
            JdyPurchaseOrder jdyPurchaseOrder = JSONUtil.toBean(jdySale, JdyPurchaseOrder.class);
            List<Task> taskList = jdyPurchaseOrder.getTasks();

            if (taskList != null && !taskList.isEmpty()) {
                // 1. 按创建时间降序排序（最新的在前）
                taskList.sort(Comparator.comparing(Task::getCreate_time).reversed());

                // 超七天确认设计次数
                int consecutiveOverdue = countConsecutiveOverdue(taskList);

                // 2. 查找最新的"设计人员确认接单"任务
                Optional<Task> latestDesignTaskOpt = taskList.stream()
                        .filter(task -> task.getFlow_id() == 20)
                        .findFirst();

                // 3. 处理找到的任务
                latestDesignTaskOpt.ifPresent(latestDesignTask -> {
                    DateTime createTime = latestDesignTask.getCreate_time();
                    if (createTime != null) {
                        // 1. 时间转换（保持原有时区处理逻辑）
                        LocalDateTime createLocalTime = LocalDateTime.parse(
                                createTime.toString(),
                                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                        ).atZone(ZoneOffset.UTC).toLocalDateTime();
                        LocalDateTime createTimePlus8h = createLocalTime.plusHours(8); // 转换为目标时区
                        LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC); // 当前UTC时间

                        // 2. 过滤周末计算工作日天数
                        long workDays = 0;
                        LocalDate startDate = createTimePlus8h.toLocalDate();
                        LocalDate endDate = now.toLocalDate();

                        // 遍历从开始日期到结束日期的每一天
                        LocalDate currentDate = startDate;

                        // 2. 已完成状态
                        if(flowState.equals("1")){
                            // 2. 获取排序后的第一个元素（即最后创建的任务）
                            Task lastTask = taskList.getFirst();
                            DateTime finishTime = lastTask.getFinish_time();
                            // 1. 时间转换（保持原有时区处理逻辑）
                            LocalDateTime createLocalTime1 = LocalDateTime.parse(
                                    finishTime.toString(),
                                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                            ).atZone(ZoneOffset.UTC).toLocalDateTime();
                            LocalDateTime createTimePlus8h1 = createLocalTime1.plusHours(8); // 转换为目标时区
                            endDate = createTimePlus8h1.toLocalDate();
                        }

                        while (!currentDate.isAfter(endDate)) {
                            DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
                            // 排除周六（SATURDAY）和周日（SUNDAY）
                            if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {
                                workDays++;
                            }
                            currentDate = currentDate.plusDays(1); // 移至下一天
                        }

                        // 3. 后续处理（保持原逻辑）
                        log.info("设计人员确认接单任务{}已持续（排除周末）: {} 个工作日", flowState , workDays);
                        bcDesignAppVO.set_widget_1751261983425(String.valueOf(workDays));
                        bcDesignAppVO.set_widget_1755584548172(String.valueOf(consecutiveOverdue));

                        Map<String, Object> parameterInster = new HashMap<>();
                        parameterInster.put("app_id", appId);
                        parameterInster.put("entry_id", entryId);
                        parameterInster.put("is_start_trigger", "true");
                        parameterInster.put("data_id", bcDesignAppVO.get_id());
                        bcDesignAppVO.set_id(null);
                        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(bcDesignAppVO));
                        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
                    }
                });
            }
        }
        return "修改了" + bcDesignAppVOList.size() + "条数据";
    }

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 统计连续相邻且flow_id都是20（int类型）的任务超时次数
     */
    public int countConsecutiveOverdue(List<Task> sortedTaskList) {
        int count = 0;
        if (sortedTaskList == null || sortedTaskList.size() < 2) {
            return count;
        }

        // 遍历原始列表，检查相邻任务
        for (int i = 0; i < sortedTaskList.size() - 1; i++) {
            Task current = sortedTaskList.get(i);
            Task next = sortedTaskList.get(i + 1);

            // 核心：判断相邻两个任务的flow_id（int）是否都是20
            if (current.getFlow_id() != 20 || next.getFlow_id() != 20) {
                continue; // 只要有一个不是20，跳过
            }

            // 校验时间字段
            if (current.getCreate_time() == null || next.getFinish_time() == null) {
                continue;
            }

            try {
                // 解析时间并计算天数差
                LocalDateTime currentCreate = LocalDateTime.parse(current.getCreate_time().toString(), DATE_FORMATTER);
                LocalDateTime nextFinish = LocalDateTime.parse(next.getFinish_time().toString(), DATE_FORMATTER);
                long daysDiff = ChronoUnit.DAYS.between(nextFinish, currentCreate);

                if (daysDiff >= 7) {
                    count++;
                    System.out.printf("超时任务对：current=%s, next=%s, 相差%d天%n",
                            current.getTask_id(), next.getTask_id(), daysDiff);
                }
            } catch (Exception e) {
                System.err.println("时间解析失败：" + e.getMessage());
            }
        }

        return count;
    }
}
